/**
 * main module
 * 
 * @author strlst <e11907086@student.tuwien.ac.at>
 * @date 2020-11-06
 * @brief the context in which the supervisor module is set up and subsequently used, additionally prints error information
 * @details none
 */

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "def.h"
#include "supervisor.h"

/**
 * @brief exits with specified exit_code after printing a specified message
 * @details message assumes a format specifier for the string 'program' parameter
 * @param message string containing the message to be printed
 * @param program string containing the program name
 * @param exit_code exit code, defined in "def.h"
 */
static inline void die(char* message, char* program, int exit_code) {
    fprintf(stderr, message, program, strerror(errno));
    exit(exit_code);
}

/**
 * @brief initiates supervisor and handles exit codes
 * @details uses exit codes defined in "def.h"
 * @param argc argument count
 * @param argv argument vector
 */
int main(int argc, char **argv) {
    switch (supervise()) {
        case OS_SHM_OPEN_FAILED:
            die("%s: error open shared memory: %s\n", argv[0], OS_SHM_OPEN_FAILED);
        case OS_SHM_CLOSE_FAILED:
            die("%s: error closing shared memory: %s\n", argv[0], OS_SHM_CLOSE_FAILED);
        case OS_MAP_FAILED:
            die("%s: error mapping shared memory: %s\n", argv[0], OS_MAP_FAILED);
        case OS_UNMAP_FAILED:
            die("%s: error unmapping shared memory: %s\n", argv[0], OS_UNMAP_FAILED);
        case OS_SHM_UNLINK_FAILED:
            die("%s: error unlinking shared memory: %s\n", argv[0], OS_SHM_UNLINK_FAILED);
        case OS_FTRUNCATE_FAILED:
            die("%s: error on ftruncate: %s\n", argv[0], OS_FTRUNCATE_FAILED);
        case OS_SEM_OPEN_FAILED:
            die("%s: error opening semaphore: %s\n", argv[0], OS_SEM_OPEN_FAILED);
        case OS_SEM_CLOSE_FAILED:
            die("%s: error closing semaphore: %s\n", argv[0], OS_SEM_CLOSE_FAILED);
        case OS_SEM_UNLINK_FAILED:
            die("%s: error unlinking semaphore: %s\n", argv[0], OS_SEM_UNLINK_FAILED);
        default:
            assert(1);
    }
    return 0;
}
